<template>
  <Modal title="轨迹回放" v-model:visible="visible" destroyOnClose :footer="null" :afterClose="afterClose" :width="1200">

    <div class="MapBox">
      <MapContainer @currentPointIndex="currentPointIndex" :arrList="flightTrajectoryList"
        :playbackInform="playbackInform"></MapContainer>
      <div class="searchBox" :class="{ 'collapsed': isCollapsed }">
        <a-input class="searchInp" style="width: 211px" @change="nameAirportChange" v-model:value="pageQuery.trackName"
          placeholder="搜索">
          <template #prefix>
            <search-outlined style="color: white;" />
          </template>
        </a-input>
        <a-range-picker class="searchPicker" :format="dateFormat" @change="selectTimeChange" v-model:value="selectTime"
          style="width: 211px"></a-range-picker>
        <div class="shrinkButtonBox">
          <div class="shrinkButton" @click="shrinkButton"></div>
        </div>
        <div class="listBox" ref="content" @scroll="handleScroll">
          <!-- <div> -->
          <div class="" :class="index == playbackInform.index ? 'boxBorder box' : 'box'" @click="selectTrack(item, index)"
            :key="item.id" v-for="(item, index) in trackList">
            <div>
              <div>{{ item.trackName }}</div>
              <div>{{ formatTime(item.trackDuration) }}</div>
            </div>
            <div @click.stop="plusPlay(item, index)">
              <div class="advertiseIcon">
                <img v-show="item.play" src="@/assets/icons/flightTrajectory/play_icon.png" />
                <img v-show="!item.play" src="@/assets/icons/flightTrajectory/suspend_icon.png" />
              </div>
            </div>
          </div>
          <!-- </div> -->
        </div>
      </div>
      <div class="currentInformAircraftBox">
        <div class="aircraftAnglBox">
          <div class="aircraftBox">
            <div class="aircraftImg">
              <img src="@/assets/icons/flightTrajectory/aircraftAngl_icon1.png">
            </div>
            <div class="textBox">
              <div class="title">绝对高度</div>
              <div class="value">{{ aircraftAltitudeInform.height }}</div>
            </div>
          </div>

          <div class="aircraftBox">
            <div class="aircraftImg">
              <img src="@/assets/icons/flightTrajectory/aircraftAngl_icon2.png">
            </div>
            <div class="textBox">
              <div class="title">机头朝向</div>
              <div class="value">{{ aircraftAltitudeInform.head }}°</div>
            </div>
          </div>

          <div class="aircraftBox">
            <div class="aircraftImg">
              <img src="@/assets/icons/flightTrajectory/aircraftAngl_icon3.png">
            </div>
            <div class="textBox">
              <div class="title">俯仰角度</div>
              <div class="value">{{ aircraftAltitudeInform.pitch }}</div>
            </div>
          </div>

          <div class="aircraftBox">
            <div class="aircraftImg">
              <img src="@/assets/icons/flightTrajectory/aircraftAngl_icon4.png">
            </div>
            <div class="textBox">
              <div class="title">GPS搜星数量</div>
              <div class="value">{{ aircraftAltitudeInform.gps_number }}</div>
            </div>
          </div>

        </div>

        <div class="trackPlaybackBarBox">

        </div>
      </div>
    </div>
  </Modal>
</template>
<script lang="ts" setup>
import { defineProps, defineEmits, ref, watch, reactive } from 'vue';
import { Modal } from 'ant-design-vue';
import { SearchOutlined } from '@ant-design/icons-vue';
import MapContainer from './MapContainer.vue'
import { trackApi, deviceApi } from '../../equipManage/deviceManageList/data.api'
import axios from "axios";
import coordtransform from 'coordtransform';
import dayjs, { Dayjs } from 'dayjs';
import { message } from 'ant-design-vue';
const emit = defineEmits();
const visible = ref<boolean>(false);
const dateFormat = 'YYYY-MM-DD';

const props = defineProps({
  open: {
    type: Boolean,
    default: false
  },
  trackPlaybackDeviceSn: {
    type: String,
  },
  isCollapsed: {
    type: Boolean,
    default: false
  }
});
//轨迹列表
let trackList = ref([])

let flightTrajectoryList = ref() //飞机轨迹

let isCollapsed = ref(props.isCollapsed) // 初始状态是展开的(false为打开)

let content = ref()
//查询数据列表
let pageQuery = reactive({
  deviceSn: '',
  pageNo: 1,
  pageSize: 10,
  trackName: null,
  startTime: null,
  endTime: null
})

let selectTime = ref<[Dayjs, Dayjs]>() // 查询选择的时间

let aircraftAltitudeInform = reactive({
  height: '0', //高度
  pitch: '0', // 俯仰角度
  gps_number: '0',
  head: '0' //机头朝向
})

let playbackInform = reactive({
  selectTrackId: '', //当前选中的轨迹id
  play: null, //是否播放
  index: null, //当前播放的索引
  firstClick: null
})

watch(
  () => props.open,
  (newValue) => {
    visible.value = newValue;
    pageQuery.deviceSn = props.trackPlaybackDeviceSn;
    if (newValue) {
      getData()
    }
  },
)

function formatTime(ms) { //毫秒转 时分秒
  const date = new Date(ms);
  return date.toISOString().substr(11, 8); // 格式化为 hh:mm:ss
}

//点击列表 获取轨迹详情
async function selectTrack(item, index) {
  if (playbackInform.index != index && playbackInform.index != null) {
    trackList.value[playbackInform.index].play = false
    playbackInform.firstClick = null
  }
  let res = await trackApi.get({ trackId: item.id })
  // let res = await trackApi.get({ trackId: '1720712324926607361' })
  // let res = await trackApi.get({ trackId: '1723955970511564802' })

  playbackInform.selectTrackId = item.id
  playbackInform.play = trackList.value[index].play
  playbackInform.index = index
  let response = await trackApi.getContent({})
  console.log("/uav/device/track/trackFileContent==", response)
  flightTrajectoryList.value = response.map((item) => {
    let latitudeLongitude = coordtransform.wgs84togcj02(item.longitude, item.latitude)
    return {
      ...item,
      longitude: latitudeLongitude[0],
      latitude: latitudeLongitude[1],
    }
  })

  // axios.get(res.trackFileUrl).then(response => {
  //   flightTrajectoryList.value = response.data.map((item) => {
  //     let latitudeLongitude = coordtransform.wgs84togcj02(item.longitude, item.latitude)
  //     return {
  //       ...item,
  //       longitude: latitudeLongitude[0],
  //       latitude: latitudeLongitude[1],
  //     }
  //   })
  //   console.log(flightTrajectoryList.value)
  // }).catch(error => {
  //   console.error("获取数据出错: " + error);
  //   message.error('飞行轨迹获取失败!');
  // });
}

//轨迹播放或者暂停
async function plusPlay(item, index) {
  if (playbackInform.selectTrackId != item.id) {
    await selectTrack(item, index)
  }
  if (playbackInform.index != index && playbackInform.index != null) {
    trackList.value[playbackInform.index].play = false
    playbackInform.firstClick = null
  }

  if (playbackInform.firstClick == null) {
    playbackInform.firstClick = true
  } else {
    playbackInform.firstClick = false
  }

  trackList.value[index].play = !trackList.value[index].play
  // playbackInform.selectTrackId = item.id
  playbackInform.play = trackList.value[index].play
  playbackInform.index = index
}

let turnPage = ref(true)

//获取列表
async function getData() {
  trackList.value = null
  playbackInform.index = null
  playbackInform.play = null
  playbackInform.firstClick = null
  playbackInform.selectTrackId = null
  try {
    turnPage.value = true
    let res = await trackApi.query(pageQuery)
    trackList.value = res.records.map((item) => {
      return {
        ...item,
        play: false,
      }
    })
    console.log(trackList.value)
  } catch {
    message.error('轨迹列表获取失败!');
    console.error("发现错误")
  }

}

async function handleScroll(event) {
  console.log(turnPage.value, 'turnPage')
  if (content.value && turnPage.value) {
    if (content.value.scrollTop + content.value.clientHeight >= content.value.scrollHeight - 20) {
      pageQuery.pageNo++
      let res = await trackApi.query(pageQuery)
      if (res.records.length > 0) {
        trackList.value.push(...res.records.map((item) => {
          return {
            ...item,
            play: false,
          }
        }))
      } else {
        turnPage.value = false
        pageQuery.pageNo = 1
        console.log('没数据了')
      }
      console.log('触底了')
    }
  }
}

let timer: ReturnType<typeof setTimeout>;
//机场名称搜索框
function nameAirportChange(event) {
  pageQuery.pageNo = 1
  if (timer) {
    clearTimeout(timer);
  }
  timer = setTimeout(() => {
    getData()
  }, 1000);
}

function selectTimeChange() {
  pageQuery.pageNo = 1
  if (selectTime.value && selectTime.value.length > 0) {
    pageQuery.startTime = dayjs(selectTime.value[0].$d).format('YYYY-MM-DD')
    pageQuery.endTime = dayjs(selectTime.value[1].$d).format('YYYY-MM-DD')
  } else {
    pageQuery.startTime = null
    pageQuery.endTime = null
  }

  getData()
}

//地图组件返回给我的index
function currentPointIndex(event) {
  console.log(event, flightTrajectoryList.value.length)
  aircraftAltitudeInform.gps_number = flightTrajectoryList.value[event].gps_number
  aircraftAltitudeInform.height = `${Math.floor(flightTrajectoryList.value[event].height)} m`
  aircraftAltitudeInform.pitch = `${Math.floor(flightTrajectoryList.value[event].attitude_pitch)}`
  aircraftAltitudeInform.head = `${Math.floor(flightTrajectoryList.value[event].attitude_head)}`
  stopPlayback()
}

let stopPlaybackTimer: ReturnType<typeof setTimeout>;
function stopPlayback() {
  if (stopPlaybackTimer) {
    clearTimeout(stopPlaybackTimer);
  }
  stopPlaybackTimer = setTimeout(() => {
    trackList.value[playbackInform.index].play = false
  }, 300);
}

function afterClose() {
  emit('close')
}

function shrinkButton() {
  isCollapsed.value = !isCollapsed.value
}

</script>
<style  lang="less" scoped>
/deep/ .full-modal {
  .ant-modal {
    max-width: 100%;
    top: 0;
    padding-bottom: 0;
    margin: 0;
  }

  .ant-modal-content {
    display: flex;
    flex-direction: column;
    height: calc(100vh);
  }

  .ant-modal-body {
    flex: 1;
  }
}

/* 滑块样式 */
::-webkit-scrollbar {
  display: none;
}

.MapBox {
  background-color: #122036;
  display: flex;
  position: relative;
  overflow: hidden;

  .collapsed {
    transform: translateX(-100%);
    /* 当抽屉收缩时，向左平移 */
  }

  .searchBox {
    // background-color: rgba(255, 255, 255, 0.1);
    backdrop-filter: blur(10px);
    position: absolute;
    height: 670px;
    width: 250px;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 12px 0;
    transition: transform 0.3s ease;
    /* 添加过渡效果 */

    .searchInp {
      background: rgba(33, 85, 145, 0.27);
      border: 1px solid #3B7EC9;
      margin-bottom: 12px;
    }

    .searchPicker {
      background: rgba(33, 85, 145, 0.27);
      border: 1px solid #3B7EC9;
      color: white;
    }

    /deep/ .ant-input {
      background: rgba(33, 85, 145, 0);
      color: white;
    }

    /deep/ .ant-picker-input>input {
      color: white;
    }

    /deep/ .anticon svg {
      color: white;
    }

    /deep/ .ant-picker-range:hover .ant-picker-clear {
      background-color: transparent;
    }

    /deep/ .ant-picker-clear {
      background-color: transparent;
    }

    .shrinkButtonBox {
      position: absolute;
      top: 50%;
      left: 106%;
      transform: translate(-50%, -50%);

      .shrinkButton {
        background-color: rgba(255, 255, 255, 0.5);
        backdrop-filter: blur(10px);
        width: 30px;
        height: 30px;
        border-radius: 0 50% 50% 0;
        cursor: pointer;
      }
    }

    .listBox {
      // height: 100%;
      // background-color: rgba(255, 255, 255, 0.1);
      backdrop-filter: blur(10px);
      margin-top: 12px;
      overflow-y: auto;

      .boxBorder {
        border: 1px solid;
      }

      .box {
        width: 211px;
        height: 67px;
        background: linear-gradient(320deg, rgba(20, 36, 60, 0.4) 0%, rgba(11, 22, 55, 0.4) 100%);
        backdrop-filter: blur(5px);
        border-radius: 4px;
        // border: 2px solid transparent;
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 0 15px;
        margin-bottom: 12px;
        font-size: 14px;
        color: #FFFFFF;
        cursor: pointer;

        .advertiseIcon {
          width: 20px;
          height: 20px;

          img {
            width: 100%;
            height: 100%;
          }
        }
      }
    }
  }

  .currentInformAircraftBox {
    position: absolute;
    transform: translate(-50%, 0%);
    // top: 50%;
    left: 50%;
    bottom: 0%;
    // background-color: #3B7EC9;

    .aircraftAnglBox {
      display: flex;
      align-items: center;
      gap: 56px;

      .aircraftBox {
        display: flex;
        align-items: center;

        .aircraftImg {
          width: 40px;
          height: 40px;
          margin-right: 12px;

          img {
            width: 100%;
            // height: 40px;
          }
        }

        .textBox {
          .title {
            font-size: 12px;
            color: #FFFFFF;
          }

          .value {
            font-size: 16px;
            color: #FFFFFF;
          }
        }
      }
    }

    .trackPlaybackBarBox {
      backdrop-filter: blur(4px);
    }
  }
}

.searchBox {
  width: 224px;
}
</style>
